<template>
  <div class="call_quality">
    <div class="cozy_tip">{{$t('intelligentQualityCheck.intelligentWarn')}}</div>
    <affix :label="$t('intelligentQualityCheck.intelCallRecord')" :quality="true" @isFold="isFold"></affix>
    <div class="wrap_con" v-show="isShowCon">
      <el-form :model="callForm" label-position="top" class="demo-form-inline" :rules="rules" ref="callForm">
        <el-form-item label="">
          <el-checkbox v-model="callForm.SKIP_QUALITY" @change="skipChange">{{$t('qualityCheck.showSkippedData')}}</el-checkbox>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item :label="$t('public.callTime')+':'" prop="beginTime">
              <el-date-picker size="mini"
                v-model.trim="callForm.beginTime"
                :id="['a','b']"
                type="datetimerange"
                :picker-options="pickerOptions2"
                :placeholder="$t('public.timeRanges')"
                align="right"
                :editable="boolean"
                @change="callTimeChange">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('call.callType')+':'">
              <el-select size="mini" v-model.trim="callForm.CONNECT_TYPE" filterable :placeholder="$t('webchat.webchatAll')">
                <el-option :label="'--'+$t('webchat.webchatAll')+'--'" value=""></el-option>
                <el-option
                  v-for="(item, index) in callTypeList"
                  :label="item.code_name"
                  :value="item.code_value"
                  :key="index"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-show="autoqcAgent">
            <el-form-item :label="$t('qualityCheck.callAgent')+':'">
              <el-popover
                ref="popover4"
                placement="bottom"
                @show="popoverShow"
                width="240"
                trigger="click">
                <agent-tree :readSeat="followedAgents" ref="agentTree" @saveFollowedAgents="saveFollowedAgents"></agent-tree>
              </el-popover>
              <div class="follow-agent-wrap" v-popover:popover4>
                <span class="follow-agent follow-common" v-for="item in followedAgents" :key="item._id">{{item.label}}
                  <i class="el-icon-close" @click.stop="closeFollowedAgents(item._id)"></i>
                </span>
                <div>
                  <span type="primary" class="follow-agent-wrap-btn"><i class="el-icon-arrow-down" style="color: #c0c4cc"></i></span>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('public.queues')+':'">
              <el-select size="mini" v-model.trim="callForm.ERROR_MEMO" filterable :placeholder="$t('webchat.webchatAll')">
                <el-option :label="'--'+$t('webchat.webchatAll')+'--'" value=""></el-option>
                <el-option
                  v-for="(item, index) in callQueueList"
                  :label="item.DisplayName"
                  :value="item.Exten"
                  :key="index"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item :label="$t('qualityCheck.callingNumber')+':'" prop="CALL_NO">
              <el-input size="mini" v-model.trim="callForm.CALL_NO" :placeholder="$t('public.pleaseEnter')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('qualityCheck.calledNumber')+':'" prop="CALLED_NO">
              <el-input size="mini" v-model.trim="callForm.CALLED_NO" :placeholder="$t('public.pleaseEnter')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="CALL_TIME_LENGTH_BEGIN" :label="$t('qualityCheck.callTimeMin')+':'">
              <el-input v-model.trim="callForm.CALL_TIME_LENGTH_BEGIN"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="CALL_TIME_LENGTH_END" :label="$t('qualityCheck.callTimeMax')+':'">
              <el-input v-model.trim="callForm.CALL_TIME_LENGTH_END"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item :label="$t('public.satisfaction')+':'">
              <!--<el-select size="mini" v-model.trim="callForm.INVESTIGATE" filterable :placeholder="'&#45;&#45;'+$t('webchat.webchatAll')+'&#45;&#45;'+':'">-->
                <!--<el-option :label="'&#45;&#45;'+$t('webchat.webchatAll')+'&#45;&#45;'" value=""></el-option>-->
                <!--<el-option-->
                  <!--v-for="(item, index) in satisfactionList"-->
                  <!--:label="item.name"-->
                  <!--:value="item.value"-->
                  <!--:key="index"-->
                <!--&gt;-->
                <!--</el-option>-->
              <!--</el-select>-->
              <!--二级满意度-->
              <!--{{investigateArray}}-->
              <el-cascader
                style="width:100%;"
                :options="investigateArray"
                v-model.trim="INVESTIGATE"
                change-on-select
                @change="changeData(INVESTIGATE)"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('public.callLabel')+':'">
              <div class="label-select-wrap">
                <label-cascader @labelSelect="labelSelect" :isNoLabel="true" :resetSelect="resetSelect" :needType="true"></label-cascader>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('call.repeatCall')+':'">
                <el-select size="mini" v-model="callForm.REPEAT_CALL" multiple :placeholder="$t('webchat.webchatAll')">
                  <el-option :label="$t('call.repeatCall24hNum')" value="24h"></el-option>
                  <el-option :label="$t('call.repeatCall48hNum')" value="48h"></el-option>
                </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="sub" style="margin-bottom: 28px">
      <el-button class="primary_btn" @click="rest">{{$t('public.reset')}}</el-button>
      <el-button type="primary" class="search primary_btn" @click="queryList">{{$t('public.search2')}}</el-button>
    </div>
    <!-- 通话质检 -->
    <call-grade :ruleRender="ruleRender" :callDialogShow="callDialogShow" v-if="callIsShow" @close="off" :flagId="flagId" :currentItemCall = "this.currentItemCall"  :currentGrade = "{}"  :template = "this.template" @saveGrade="saveGrade" @nextGrade="nextGrade" :qcResectLabel="qcResectLabel" @saveGradeAnd="saveGradeAnd" :refreshCallGrade="refreshCallGrade"></call-grade>
    <affix :label="$t('public.searchResult')"></affix>
    <div class="sub">
      <el-button type="primary" class="primary_btn" @click="QCcheck">{{$t('intelligentQualityCheck.intelligentQua')}}</el-button>
      <el-button class="primary_btn" @click="setHeaderConfig">{{$t('report.setHeaderConfig')}}</el-button>
    </div>
    <div class="wrapper_table">
      <div class="wrap_page clearfix">
        <div class="choose fl">
          <span>{{checked ? $t('intelligentQualityCheck.checkIntelligentAll'): $t('intelligentQualityCheck.checkIntelligentCount', {arrChooseTab: arrChooseTab.length})}}</span>
          <span @click="cancelChoose" class="not_choose" v-if="arrChooseTab.length">{{$t('intelligentQualityCheck.intelCancelChoose')}}</span>
          <el-checkbox v-model="checked" @change="checkAll">{{$t('public.checkAll')}}</el-checkbox>
          <span style="display: inline-block;margin-left: 30px;color: #459ae9;font-size: 12px;" v-if="arrChooseTab.length">{{$t('intelligentQualityCheck.intelligentWarn2')}}</span>
        </div>
        <div class="search-pagination fr">
          <div :class="{page_mask:arrChooseTab.length}"></div>
          <pagination
                  :moreFlag="moreNorFlag"
                  :allCount="allCount"
                  :small="pagination.small"
                  :currentPage="pagination.currentPage"
                  :count="count"
                  :noJump="true"
                  @turnPage="turnPage"
                  :totalPage="totalPage"
                  @getAllCount="getAllCount"
                  >
          </pagination>
        </div>
      </div>
      <base-table @checkData="checkData" ref="qualityTable" :tableData="tableData" :options="tableDataHeader.Config" @grade="handle" @viewLook="look"></base-table>
    </div>
    <div class="looklog">
        <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :visible.sync="isShow" :title="title">
          <div class="tables">
          <div class="deploy">
            <div class="search-pagination">
              <pagination
                      :small="paginationRecord.small"
                      :currentPage="paginationRecord.currentPage"
                      :count="countRecord"
                      @turnPage="turnPageRecord"
                      :totalPage="totalPageRecord"
                      >
              </pagination>
            </div>
          </div>
          <el-table :data="recordList" size="mini">
            <el-table-column prop="user" :label="listenpp" width="">
            </el-table-column>
            <el-table-column prop="" label="" width="">
            </el-table-column>
            <el-table-column prop="time" :label="listenTime" width="">
            </el-table-column>
          </el-table>
        </div>
      </el-dialog>
    </div>
    <!--配置表头-->
    <header-option v-show="isShowTableConfig" :show="isShowTableConfig" :option="headOptions" :type="tableConfigType" v-on:close="closeTableConfig"></header-option>
    <qc-dialog :dialogVisible="dialogVisible" :Qclists="Qclists" @comitQc="comitQc" @closeQcDialog="closeQcDialog"></qc-dialog>
    <el-dialog
      :title="$t('intelligentQualityCheck.intelCarryOut')"
      :visible="dialogVisibleOne"
      width="30%"
      :close-on-click-modal="false"
      @close="closeQcDialog">
      <span v-if="quaCheckIsSuccess">{{$t('intelligentQualityCheck.intelTaskCommit')}}</span>
      <span v-if="!quaCheckIsSuccess">{{$t('intelligentQualityCheck.quaCheckFail')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleOne=false" class="primary_btn">{{$t('public.Iknow')}}</el-button>
        <el-button v-if="quaCheckIsSuccess" type="primary" @click="goQualityRes" class="primary_btn">{{$t('intelligentQualityCheck.intelAtOnceGo')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import Pagination from '@/components/public-modules/card/Pagination'
  import AgentTree from '@/components/business-modules/qualityCheck/base/qualityAgentTree'
  import affix from '../../../ui-modules/affix/Affix.vue'
  import CallGrade from './CallGrade'
  import qcDialog from './qcDialog'
  import {deepClone, getCache, getDateTime, scopeAgents, m7Language, isHasFunc} from '@/utils/m7Utils.js'
  import {checkform} from '@/utils/validate.js'
  import LabelCascader from '@/components/public-modules/phone-bar/LabelCascader.vue'
  import headerOption from '../../report/base/headerOption.vue'
  import BaseTable from '../qualityTable/qualityTable.vue'
  export default {
    name: 'call_quality',
    data () {
      let validate1 = (rule, value, callback) => {
        if (value !== '') {
          let match = checkform(value, 'Number3')
          if (match) {
            callback(new Error(this.$t('qualityCheck.pleaseEnterRightNum')))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
      let validate2 = (rule, value, callback) => {
        if (value !== '') {
          let match = checkform(value, 'Number3')
          if (match) {
            callback(new Error(this.$t('qualityCheck.pleaseEnterPositiveInteger')))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
      return {
        callPages: 0,
        listNum: 0,
        checked: false,
        ruleRender: [],
        Qclists: [],
        quaCheckIsSuccess: true,   //   提交智能质检是否成功
        dialogVisibleOne: false,
        dialogVisible: false,
        arrChooseTab: [],
        isShowTableConfig: false,   //   配置表头
        tableConfigType: 'quality_call_table_title',
        moreNorFlag: false, // table翻页组件开始
        allCount: 0,
        pagination: {
          small: false,
          currentPage: 1
        },
        currentId: '', // 查看日志start
        title: '',
        countRecord: 0,
        listenTime: '',
        listenpp: '',
        headOptions: {},
        paginationRecord: {
          small: false,
          currentPage: 1
        },
        isShow: false,
        totalPageRecord: 1, // end
        recordList: [],
        tableData: [],
        callDialogShow: false,
        callIsShow: false, // 通话评分
        flagId: 'normal',
        currentItemCall: {},
        tableDataHeader: {
          Config: [{ 'order': '1', 'name': 'CALL_NO_SHOW', 'displayname': '主叫号码', 'show': true }, { 'order': '2', 'name': 'DISPOSAL_AGENT', 'displayname': '接听座席', 'show': true }, { 'order': '3', 'name': 'CALLED_NO_SHOW', 'displayname': '被叫号码', 'show': true }, { 'order': '4', 'name': 'CONNECT_TYPE_show', 'displayname': '呼叫类型', 'show': true }, { 'order': '5', 'name': 'ERROR_MEMO', 'displayname': '呼入技能组', 'show': true }, { 'order': '6', 'name': 'INVESTIGATE', 'displayname': '满意度', 'show': true }, { 'order': '7', 'name': 'OFFERING_TIME', 'displayname': '呼叫时间', 'show': true }]
        },
        template: {
          type: 'pass'
        },
        isSave: false,
        qcResectLabel: false,
        refreshCallGrade: 0,
        boolean: false,
        isShowCon: false,
        callTypeList: [], // 通话类型
        callAgentList: [], // 通话座席
        callQueueList: [], // 技能组
        satisfactionList: [],
        labelType: 'single',
        autoqcAgent: false,     //  通话座席筛选条件是否展示
        resetSelect: false,
        callForm: {
          SKIP_QUALITY: false,   //  获取被跳过的
          beginTime: '',
          CONNECT_TYPE: '',
          DISPOSAL_AGENT: '',
          ERROR_MEMO: '',
          CALLED_NO: '',
          CALL_NO: '',
//          INVESTIGATE: '',
          singleLabel: '',
          CALL_TIME_LENGTH_BEGIN: '',
          CALL_TIME_LENGTH_END: '',
          REPEAT_CALL:[]
        },
        investigateArray: [],//  二级满意度数据
        INVESTIGATE: [],  //  二级满意度条件
        rules: {
          CALL_NO: [
            {validator: validate1, trigger: 'blur'}
          ],
          beginTime: [
            {required: true, message: this.$t('customer.CustomerSearch.pleaseChooseTime'), trigger: 'change'}
          ],
          CALLED_NO: [
            {validator: validate1, trigger: 'blur'}
          ],
          CALL_TIME_LENGTH_BEGIN: [
            {validator: validate2, trigger: 'blur'}
          ],
          CALL_TIME_LENGTH_END: [
            {validator: validate2, trigger: 'blur'}
          ],
          msgCount: [
            {validator: validate2, trigger: 'blur'}
          ]
        },
        pickerOptions2: {
          disabledDate(time) {
              return time.getTime() > Date.now() - 600*1000
          },
          shortcuts: [{
            text: this.$t('sms.thisOneWeek'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              end.setTime(end.getTime() - 600 * 1000)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: this.$t('sms.thisOneMonth'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              end.setTime(end.getTime() - 600 * 1000)
              picker.$emit('pick', [start, end])
            }
          }]
        },
      }
    },
    props: {
      refreshNum: Number
    },
    computed: {
      count () {
        if (this.$store.state.qualityCheck.intelSearchList.qcMore) {
          this.moreNorFlag = true
        } else {
          this.moreNorFlag = false
        }
        return this.$store.state.qualityCheck.intelSearchList.qcCount
      },
      tempList () {
        return this.$store.state.qualityCheck.tempListAuto
      },
      totalPage () {
        return Math.ceil(this.$store.state.qualityCheck.intelSearchList.qcCount / 10) || 0
      },
      //坐席展示数据
      followedAgents () {
        let agents = this.callForm.DISPOSAL_AGENT || []
        let agentsAll = this.$store.getters.agents || {}
        return agents.map((item) => {
          return {_id: item, label: agentsAll[item].displayName}
        })
      },
    },
    components: {
      affix,
      qcDialog,
      headerOption,
      Pagination,
      CallGrade,
      BaseTable,
      LabelCascader,
      AgentTree
    },
    methods: {
      //通话坐席树形框
      popoverShow () {
        this.$refs.agentTree.setCheckedKeys()
      },
      //坐席保存
      saveFollowedAgents (agents) {
        this.callForm.DISPOSAL_AGENT = deepClone(agents)
        document.getElementsByTagName('body')[0].click()
      },
      //坐席删除
      closeFollowedAgents (agent) {
        this.callForm.DISPOSAL_AGENT = this.callForm.DISPOSAL_AGENT.filter((item) => item !== agent)
      },
      checkAll (bool) {
        console.log(this.refreshNum)
        if (bool) {
          console.log(111111111111)
          this.$refs.qualityTable.toggleSelection(this.tableData)
          this.arrChooseTab = ['1']
        } else {
          this.$refs.qualityTable.cancleChoose()
          this.arrChooseTab = []
        }
        this.checked = bool
      },
      // 跳过数据
      skipChange () {
        this.query()
      },
      // 跳转结果页
      goQualityRes () {
        this.closeQcDialog()
        this.$router.push({
          path: '/index/intelligentQualityCheck/quality_check_result',
          name: 'qualityCheckResult',
          params: {
            webOrCallOrTaskTemp: 1
          }
        })
      },
      // 执行智能质检
      comitQc (arr) {
        let data1 = {
          type: 'call',
          taskList: [],
          rule: arr
        }
        if (this.checked) {
          let form = this.qu
          form.cdrId = 'autoqc_query'
          this.$store.dispatch('normalCallSearch1', form).then((res) => {
            this.listNum = res.count
          }).then(() => {
            console.log(this.listNum)
            if (this.listNum > 0) {
              return
            }
          })
          delete data1.taskList
          this.$refs.callForm.validate((valid) => {
            if (valid) {
              if (Number(this.callForm.CALL_TIME_LENGTH_BEGIN) && Number(this.callForm.CALL_TIME_LENGTH_END) && Number(this.callForm.CALL_TIME_LENGTH_BEGIN) >= Number(this.callForm.CALL_TIME_LENGTH_END)) {
                this.$message.error(this.$t('qualityCheck.PleaseEnterTheCorrectCallDurationRrange'))
                return
              }
              this.callForm.cdrId = 'autoqc_query'
              if (this.callForm.beginTime.length !== 0) {
                let sTime = this.callForm.beginTime[0].getTime()
                let eTime = this.callForm.beginTime[1].getTime()
                let oneDay = 1000 * 3600 * 24
                let Days = parseInt((eTime - sTime) / oneDay)
                if (Days > 31) {
                  this.$message.error(this.$t('intelligentQualityCheck.intelCallOutTimeTip'))
                  return
                }
              } else {
                this.$message.error('请您选择呼叫时间, 范围不能大于一个月')
                return
              }
              if (this.callForm.beginTime && this.callForm.beginTime[0] !== null) {
                this.callForm.BEGIN_TIME = getDateTime(this.callForm.beginTime[0])
              }
              if (this.callForm.beginTime && this.callForm.beginTime[1] !== null) {
                this.callForm.END_TIME = getDateTime(this.callForm.beginTime[1])
              }
              this.callForm.pageSize = 10
              let data = deepClone(this.callForm)
              delete data.beginTime
              let _qu = deepClone(data)
              _qu.queryCount = true
              this.qu = _qu
              this.allCount = 0
              data.searchType = 'autoqc'
              data1.query = data
              this.$store.dispatch('addTask', data1).then((res) => {
                if (res.success) {
                  this.dialogVisibleOne = true
                  this.query()
                }
              })
              this.isSave = false
            }
          })
          return
        }
        for (let i = 0; i < this.arrChooseTab.length; i++) {
          data1.taskList.push(this.arrChooseTab[i]._id)
        }
        this.quaCheckIsSuccess = true
        this.$store.dispatch('addTask', data1).then((res) => {
          if (res.success) {
            // this.closeDia()
            this.dialogVisibleOne = true
          } else {
            this.quaCheckIsSuccess = false
            this.dialogVisibleOne = true
//            this.closeQcDialog()
          }
          this.query()
        })
      },
      closeDia () {
        this.dialogVisibleOne = true
        this.dialogVisible = false
      },
      closeQcDialog () {
        this.dialogVisible = false
        this.dialogVisibleOne = false
      },
      // 智能质检按钮
      QCcheck () {
        this.Qclists = []
        if (!this.arrChooseTab.length && !this.checked) {
          this.$message.error(this.$t('intelligentQualityCheck.intelPleaChooseQc'))
          return
        }
        if (this.checked) {
          // 判断质检的条数
          let form = this.qu
          form.cdrId = 'autoqc_query'
          this.$store.dispatch('normalCallSearch1', form).then((res) => {
            this.listNum = res.count
            if (this.listNum > 10000) {
              this.$message.error(this.$t('intelligentQualityCheck.intelMaxNum'))
              return
            } else if (this.listNum === 0) {
              this.query()
              this.$message.error(this.$t('intelligentQualityCheck.intelPleaChooseQc'))
              return
            } else {
              this.QcChechShow()
            }
          })
        } else {
          this.QcChechShow()
        }
      },
      // 满足质检条件之后展示
      QcChechShow () {
        let data1 = {
          isEnable: true
        }
        this.$store.dispatch('getRuleLessList', data1).then((res) => {
          if (res.success) {
            // 过滤下类型
            res.data = res.data.filter((item) => {
              return item.type === 'call'
            })
            for (var i = 0; i < res.data.length; i++) {
              this.Qclists.push({
                name: res.data[i].name,
                value: res.data[i]._id
              })
            }
          }
        })
        // this.$router.push({path: '/index/report/call_report/callin_report'})
        this.dialogVisible = true
      },
      setHeaderConfig () {
        this.$store.dispatch('getReportTableHeader', 'quality_call_table_title').then((res) => {
          this.headOptions = res
          this.tableConfigType = 'quality_call_table_title'
          this.isShowTableConfig = !this.isShowTableConfig
        })
      },
      closeTableConfig (data) {
        this.isShowTableConfig = false
        if (data === 'save') {
          this.query()
        }
      },
      // 取消全选
      cancelChoose () {
        this.$refs.qualityTable.cancleChoose()
        this.checked = false
      },
      checkData (arr) {
        console.log(arr)
        this.arrChooseTab = arr
        this.checked = false
      },
      // 保存评分
      saveGrade (data) {
        this.isSave = true
        this.$store.dispatch('submitOneManulQcCall', data).then((res) => {
          if (res.success) {
            this.off()
            this.$message.success(this.$t('intelligentQualityCheck.intelGradeSuccess'))
          }
        })
      },
      saveGradeAnd (data) {
        this.isSave = true
        this.$store.commit('deleteGraded/qualityCheckAuto', this.currentIndex)
        this.$store.dispatch('submitOneManulQcCall', data).then((res) => {
          if (res.success) {
            this.off()
            this.$message.success(this.$t('intelligentQualityCheck.intelGradeSuccess'))
            // 删除tempList评价完的那个
            this.$store.commit('deleteGraded/qualityCheckAuto', 1)
            // 判断是否还有没质检了
            if (this.tempList.length <= 0) {
              this.$message.success(this.$t('qualityCheck.allRatingFinish'))
              this.query()
            } else {
              this.$message.success(this.$t('qualityCheck.rateSuccessNext'))
              this.handle(this.tempList[0])
            }
          }
        })
      },
      // 查看日志列表
      queryRecordCallListenLog (_id, page) {
        this.currentId = _id
        this.title = this.$t('qualityCheck.callQualityLookLog')
        this.listenpp = this.$t('qualityCheck.checkPeople')
        this.listenTime = this.$t('qualityCheck.checkTime1')
        this.$store.dispatch('queryRecordCallListenLog', {'CALL_SHEET_ID': _id, 'page': page, 'pageSize': 10}).then(() => {
          console.log(this.$store.state.qualityCheck)
          this.recordList = this.$store.state.qualityCheck.recordList.list
          this.countRecord = this.$store.state.qualityCheck.recordList.count
          this.totalPageRecord = Math.ceil(this.$store.state.qualityCheck.recordList.count / 10) || 0
          this.isShow = true
        })
      },
      // 查看日志传上来的事件
      look (_id) {
        this.paginationRecord.currentPage = 1
        this.countRecord = 0
        this.totalPageRecord = 0
        this.queryRecordCallListenLog(_id, 1)
      },
      // 获取所有表格数据
      getAllCount () {
        this.allCount = 0
        let form = this.qu
        form.cdrId = 'autoqc_query'
        const more = false
        this.$store.dispatch('normalCallSearch1', form).then((res) => {
          this.allCount = res.count
          let type = 'qc'
          this.$store.commit('qualityCheck/SET_QUAL_MORE', {more, type})
        })
      },
      // 质检翻页
      turnPage (pageNum) {
        if (this.$store.state.qualityCheck.intelSearchList.type === 'normalCallCheck') {
          this.allCount = 0
          this.pagination.currentPage = pageNum
          //   翻页  morePage
          let morePage = 1
          if (pageNum > 1) {
            morePage = Math.floor(pageNum / this.callPages + 1)
          }
          this.callForm.morePage = morePage
          this.callForm.page = pageNum
          this.getNormalCallsheetData()
        }
      },
      // 查看日志翻页
      turnPageRecord (pageNum) {
        this.paginationRecord.currentPage = pageNum
        this.queryRecordCallListenLog(this.currentId, pageNum)
      },
      // 下一个评分
      nextGrade () {
        this.isSave = true
        let passId = this.tempList[this.currentIndex]._id
        this.$store.dispatch('skipQualityCallSheet', {_id: passId})
        this.$store.commit('deleteGraded/qualityCheckAuto', this.currentIndex)
        this.$store.commit('deleteGraded/qualityCheckAuto', 1)
        if (this.tempList.length <= 0) {
          this.$message.success(this.$t('qualityCheck.allRatingFinish'))
          this.callDialogShow = false
          this.query()
        } else {
          this.$message.success(this.$t('qualityCheck.nextGrade'))
          this.handle(this.tempList[0])
        }
      },
      // 关闭弹窗
      off () {
        let play = document.getElementById('quality-autoplay_' + this.flagId + '_old')
        if (play) {
          play.pause()
        }
        this.callDialogShow = false
        this.qcResectLabel = false
        if (this.isSave === true) {
          this.query()
        }
      },
      // 组件评分传上来的事件
      handle (data) {
        this.currentIndex = 0
        for (let i = 0; i < this.tempList.length; i++) {
          if (this.tempList[i]._id === data._id) {
            this.currentIndex = i
            break
          }
        }
        if (data.REPEAT_CALL) {
          data.repeatCall = data.REPEAT_CALL === '48h' ? this.$t('call.repeatCall48h') : this.$t('call.repeatCall24h')
        } else {
          data.repeatCall = '--'
        }
        var num = this.tempList.length - this.currentIndex
        if (num < 5) {
          setTimeout(this.getMoreQualityCheckCallSheet, 1000)
        }
        this.$store.dispatch('recordListenLog', {CALL_SHEET_ID: data._id})
        this.callDialogShow = true
        this.qcResectLabel = true
        let self = this
        this.$store.dispatch('queryBusiness', {callId: data._id, customer: data.CUSTOMER_ID}).then((res) => {
          this.recordFileName(data.fileServer, data.recordFileName, data.PBX, function (url) {
            data.audio = url
            if (res && res.length > 0) {
              data.busHistory = [res[0]]
            } else {
              data.busHistory = []
            }
            self.currentItemCall = data
            self.refreshCallGrade = Math.random()
            self.callIsShow = true
          })
        })
      },
      getMoreQualityCheckCallSheet () {
        this.callForm.cdrId = 'autoqc_query'
        if (this.callForm.beginTime && this.callForm.beginTime[0] !== null) {
          this.callForm.BEGIN_TIME = getDateTime(this.callForm.beginTime[0])
        }
        if (this.callForm.beginTime && this.callForm.beginTime[1] !== null) {
          this.callForm.END_TIME = getDateTime(this.callForm.beginTime[1])
        }
        this.callForm.pageSize = 10
        let form = deepClone(this.callForm)
        this.$store.dispatch('getMoreQualityCheckCallSheet', {data: form, tempList: this.tempList, type: 'call', searchType: 'autoqc'})
      },
      recordFileName (server, name, pbx, callBack) {
        if (!server) {
          callBack('')
          return
        }
        if (server.indexOf('record.7moor.com') > -1 || server.indexOf('m7-record.oss-cn-hangzhou') > -1 || server.indexOf('aliyuncs.com') > -1) {
          server = 'https' + server.substr(server.indexOf(':'), server.length)
          callBack(server + '/' + name)
        } else if (document.location.protocol === 'https:') {
          if (pbx) {
            getCache('accountPbx', pbx, this, function (pbxObj) {
              if (pbxObj) {
                if (pbxObj.assDomain) {
                  let assDomain = pbxObj.assDomain
                  if (assDomain.substr(assDomain.length - 1, assDomain.length) === '/') {
                    assDomain = assDomain.substr(0, assDomain.length - 1)
                  }
                  server = assDomain
                }
              }
              callBack(server + '/' + name)
            })
          } else {
            callBack(server + '/' + name)
          }
        } else {
          callBack(server + '/' + name)
        }
      },
      // 重置
      rest () {
        for (let i in this.callForm) {
          this.callForm[i] = ''
        }
        this.INVESTIGATE = []
        this.resetSelect = true
      },
      // 查询渲染
      getNormalCallsheetData () {
        this.callForm.cdrId = 'autoqc_query'
        if (this.callForm.beginTime && this.callForm.beginTime[0] !== null) {
          this.callForm.BEGIN_TIME = getDateTime(this.callForm.beginTime[0])
        }
        if (this.callForm.beginTime && this.callForm.beginTime[1] !== null) {
          this.callForm.END_TIME = getDateTime(this.callForm.beginTime[1])
        }
        this.callForm.pageSize = 10
        let data = deepClone(this.callForm)
        let _qu = deepClone(data)
        _qu.queryCount = true
        this.qu = _qu
        this.allCount = 0
        data.searchType = 'autoqc'
        this.$store.dispatch('normalCallSearch', data).then((res) => {
          if (data.page === 1 && this.count) {
            this.callPages = this.count / 10
          }
          const list = res.list || []
          if (list.length === 0) {
            if (res.more) {
              this.turnPage(1)
            } else {
              if (!res.count) {
                // 第一页且count为0是不再发请求
                this.pagination.currentPage = 1
                this.callForm.morePage = 1
              } else {
                let page = Math.ceil(res.count / data.pageSize)
                this.callForm.page = page
                this.pagination.currentPage = page
                this.turnPage(page)
                return false
              }
            }
          }
          this.tableData = list
          this.tableData.forEach(item => {
            if (item.INVESTIGATE || item.INVESTIGATE === 0) {
              for (let n = 0; n < this.investigateArray.length; n++) {
                if (this.investigateArray[n].value === item.INVESTIGATE) {
                  item.INVESTIGATE_show = this.investigateArray[n].label || ''
                  if (item.CHILD_INVESTIGATE || item.CHILD_INVESTIGATE === 0) {
                    if (this.investigateArray[n].children.length > 0) {
                      this.investigateArray[n].children.forEach(one => {
                        if (one.value === item.CHILD_INVESTIGATE) {
                          item.INVESTIGATE_show = item.INVESTIGATE_show + '/' + one.label
                        }
                      })
                    }
                  }
                  break
                }
              }
            }
          })
          this.tableDataHeader = res.tableHeader
        })
      },
      queryList () {
        this.pagination.currentPage = 1
        this.callForm.page = 1
        this.callForm.morePage = 1
        this.query()
      },
      query () {
        // this.pagination.currentPage = 1
        // this.callForm.page = 1
        // this.callForm.morePage = 1
        if (!this.$refs.callForm) {
          return
        }
        this.$refs.callForm.validate((valid) => {
          if (valid) {
            if (Number(this.callForm.CALL_TIME_LENGTH_BEGIN) && Number(this.callForm.CALL_TIME_LENGTH_END) && Number(this.callForm.CALL_TIME_LENGTH_BEGIN) >= Number(this.callForm.CALL_TIME_LENGTH_END)) {
              this.$message.error(this.$t('qualityCheck.PleaseEnterTheCorrectCallDurationRrange'))
              return
            }
            if (this.callForm.beginTime.length !== 0) {
              let sTime = this.callForm.beginTime[0].getTime()
              let eTime = this.callForm.beginTime[1].getTime()
              let oneDay = 1000 * 3600 * 24
              let Days = parseInt((eTime - sTime) / oneDay)
              if (Days > 31) {
                this.$message.error(this.$t('intelligentQualityCheck.intelCallOutTimeTip'))
                return
              }
            } else {
              this.$message.error('请您选择呼叫时间, 范围不能大于一个月')
              return
            }
            this.getNormalCallsheetData()
            this.isSave = false
          }
        })
      },
      callTimeChange (value) {
        if (!value) {
          this.callForm.beginTime = ''
          this.callForm.BEGIN_TIME = ''
          this.callForm.END_TIME = ''
        }
      },
      isFold (bool) {
        this.isShowCon = bool
      },
      // 通话标签
      labelSelect (data) { // 子组件外抛出来的表单
        this.resetSelect = false
        if (data.type === 'single') {
          this.labelType = 'single'
          delete this.callForm.multiLabel
          this.callForm.singleLabel = data.arr[0] || ''
        } else {
          this.labelType = 'multi'
          delete this.callForm.singleLabel
          this.callForm.multiLabel = data.arr && data.arr[0] ? data.arr : []
          delete this.callForm.singleLabel
        }
      },
      //      二级满意度条件
      changeData (selectValue) {
        console.log(selectValue)
        if (Array.isArray(selectValue)) {
          this.callForm.INVESTIGATE = selectValue[0]
          if (selectValue.length > 1) {
            this.callForm.CHILD_INVESTIGATE = selectValue[1]
          } else {
            this.callForm.CHILD_INVESTIGATE = selectValue[1] = ''
          }
        }
      }
    },
    beforeMount () {
      // 通话类型
      this.$store.dispatch('getCache', {type: 'callType'}).then((res) => {
        let callTypeListData = deepClone(res)
        callTypeListData = callTypeListData.filter(item => {
          item.code_name = m7Language('globalChineseKey.' + item.code_name, null, true) || item.code_name
          return item
        })
        this.callTypeList = callTypeListData
      })
      // 通话座席
      this.$store.dispatch('getCache', {type: 'agents'}).then((res) => {
        let agents = scopeAgents('qc', res)
        agents.forEach((item) => {
          item.labelCall = item.displayName + '【' + item.exten + '】'
        })
        this.callAgentList = agents
      })
//      满意度
      this.$store.dispatch('getCache', {type: 'investigate'}).then((res) => {
        let arrFirst = [{label: this.$t('public.all'), value: ''},{label: this.$t('public.unevaluated'), value: 'unevaluated'}]
        this.investigateArray = generateNewKeyValue(res, ['name', 'value', 'children'], ['label', 'value', 'children'], arrFirst)
      })
      // 技能组
      this.$store.dispatch('getCache', {type: 'queues'}).then((res) => {
        this.callQueueList = res
      })
      this.$store.dispatch('getCache', {type: 'options'}).then((res) => {
        let _dics = []
        for (let i = 0; i < res.length; i++) {
          var obj = res[i]
          if (obj.name && obj.name === '满意度调查选项') {
            _dics = obj.options || []
            break
          }
        }
        for (let n = 0; n < _dics.length; n++) {
          if (_dics[n] && _dics[n].name && _dics[n].options[0]) {
            this.satisfactionList.push({name: _dics[n].name, value: _dics[n].options[0].name})
          }
        }
      })
      let data = {
        page: 1,
        pageSize: 200
      }
      // 渲染质检辅助信息
      this.$store.dispatch('getMarkRuleListConfig', data).then(res => {
        if (res.success) {
          res.data = res.data.filter((item) => {
            return item.type === 'call' && item.isEnable
          })
          this.ruleRender = deepClone(res.data)
        }
      })
      let data1 = {
        isEnable: true
      }
      this.$store.dispatch('getRuleLessList', data1).then((res) => {
        if (res.success) {
          // 过滤下类型
          res.data = res.data.filter((item) => {
            return item.type === 'call'
          })
          for (var i = 0; i < res.data.length; i++) {
            this.Qclists.push({
              name: res.data[i].name,
              value: res.data[i]._id
            })
          }
        }
      })
      let startDate = new Date()
      let endDate = new Date()
      startDate.setTime(startDate.getTime() - 3600 * 1000 * 24 * 30)
      endDate.setTime(endDate.getTime() - 600 * 1000)
      this.callForm.beginTime = [startDate, endDate]
      if (isHasFunc('func_call_autoqc_agent', this.$store.state.session.user)) {
        this.autoqcAgent = true
      }
      this.callForm.page = 1
      this.callForm.morePage = 1
      this.getNormalCallsheetData()
    },
    activated () {
      this.query()
    },
    watch: {
      refreshNum () {
//        this.query()
      }
    }
  }
  function generateNewKeyValue (list, oldKeys, newKeys, label, flag, currentType) { // 数据类型转换
    let result = []
    if (!Array.isArray(list) || !Array.isArray(oldKeys) || !Array.isArray(newKeys) || oldKeys.length !== newKeys.length) {
      return result
    }
    if (Array.isArray(label)) {
      result = deepClone(label)
    } else if (label) {
      result = [{label: label, value: ''}]
    }
    for (let i = 0; i < list.length; i++) {
      let item = {}
      if (flag) {
        list[i].code_name = m7Language('globalChineseKey.' + list[i].code_name, null, true) || list[i].code_name
      }
      for (let j = 0; j < oldKeys.length; j++) {
        let oldKey = oldKeys[j]
        let newKey = newKeys[j]
        // 递归处理多级数据
        if (Array.isArray(list[i][oldKey])) {
          if (list[i][oldKey].length > 0) {
            item[newKey] = generateNewKeyValue(list[i][oldKey], ['name', 'value'], ['label', 'value'])
          }
        } else {
          item[newKey] = list[i][oldKey]
        }
      }
      result.push(item)
    }
    return result
  }
</script>
<style lang="stylus" scoped>
@import "../../../../assets/common.styl"
  .call_quality
    .label-select-wrap .select-wrap
        width 100%
        /deep/.el-cascader
          width 100%
    .cozy_tip
      color $c-main
      margin-bottom 20px
    .ui-affix
      padding-bottom 2px
    .wrapper_table
      padding-bottom 30px
      .search-pagination
        position: relative
        .page_mask
          position: absolute
          width 100%
          height 100%
          cursor: no-drop
      .choose
        font-size 14px
        .el-checkbox
          margin-left 12px
      .not_choose
        color $c-main
        cursor: pointer
        margin-left 14px
    .sub
      text-align right
      margin-bottom 10px
    .demo-form-inline
      .el-form-item
        width 100%
        height 100%
        .el-select, .el-date-editor, .el-input
          width 100%
          height 100%
    .follow-agent-wrap
      float left
      width: calc(100% - 14px)
      cursor pointer
      border-radius 5px
      border 1px solid #dcdfe6
      padding 8px 8px 6px 4px
      margin-top 6px
      overflow hidden
    .follow-common
      float left
      position relative
      line-height 24px
      background-color #7ab8f3
      margin 0 0 10px 10px
      padding 0 10px
      color #fff
      border-radius 4px
    .follow-agent-add
      cursor pointer
    .el-icon-close
      font-size 12px
    .follow-agent
      color #fff
      margin 0 0 8px 8px
      font-size 12px
      &:hover
        .el-icon-close
          display block
      .el-icon-close
        display none
        position absolute
        right -10px
        top -10px
        width 24px
        height 24px
        font-size 12px
        line-height 24px
        transform scale(0.6)
        text-align center
        color #fff
        background-color #0f99fc
        border-radius 50%
        border 1px solid #cce6ff
        cursor pointer
    .follow-agent-wrap-btn
      display block !important
      line-height 0px
      float right
      cursor pointer
      color $c-main
</style>
